package com.app.reptile.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

public class CrawlerUtils {

    public static Map<String, String> parseUrlParameters(String url) throws URISyntaxException, UnsupportedEncodingException {
        Map<String, String> params = new HashMap<>();
        URI uri = new URI(url);
        String query = uri.getQuery();
        if (query == null) {
            return params;
        }

        String[] pairs = query.split("&");
        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            // 分割键和值
            String key = idx > 0 ? pair.substring(0, idx) : pair;
            String value = idx > 0 && pair.length() > idx + 1 ? pair.substring(idx + 1) : "";
            // URL解码
            key = URLDecoder.decode(key, "UTF-8");
            value = URLDecoder.decode(value, "UTF-8");
            params.put(key, value);
        }
        return params;
    }
    public static int getRandomNum(){
        int min = 8000, max = 15000;
        return getRandomNum(min,max);
    }

    public static int getRandomNum(int min,int max){
        Random random = new Random();
        return random.nextInt(max-min+1)+min;
    }

    /**
     * 去除jquery前面字符串获取json对象
     *
     * @param result
     * @return
     * @Description: trimJquery
     * @date 2019年11月16日 上午11:22:31
     */
    public static StringBuilder trimJquery(String result) {
        StringBuilder builder = new StringBuilder();
        boolean flag = false;
        for (int k = 0; k < result.length() - 2; k++) {
            char v = result.charAt(k);
            char _v = '(';
            if (flag) {
                builder.append(v);
            }
            if (_v == v && !flag) {
                flag = true;
            }
        }
        return builder;
    }


    /**
     * 去除jquery前面字符串获取json对象
     *
     * @param result
     * @return
     * @Description: trimJquery
     * @date 2019年11月16日 上午11:22:31
     */
    public static StringBuilder trimJquery(String result,char key) {
        StringBuilder builder = new StringBuilder();
        boolean flag = false;
        for (int k = 0; k < result.length() - 2; k++) {
            char v = result.charAt(k);
            char _v = key;
            if (flag) {
                builder.append(v);
            }
            if (_v == v && !flag) {
                flag = true;
                builder.append(v);
            }
        }
        int index = builder.toString().lastIndexOf("}");

        return builder.delete(index+1,builder.length());
    }

    /**
     * 处理股票信息数据
     * @param cxt
     * @return
     */
    public static String dealRicheInfo(String cxt){
        String mainBusiness = null;
        Document document = Jsoup.parse(cxt);
        Elements elements = document.select("script");

        for(Element element : elements){
            String id = element.attr("id");
            String type = element.attr("type");
            if (StringUtils.isNotBlank(id) && "application/json".equals(type)){

                try{
                    String html = element.html();
                    ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
                    JSONObject jsonObject = JSONObject.parseObject(html);
                    ParserConfig.getGlobalInstance().setAutoTypeSupport(false);
                    JSONObject data =jsonObject.getJSONObject("data");
                    if (Objects.nonNull(data)){
                        JSONArray jsonArray = data.getJSONArray("tabs");
                        if (Objects.nonNull(jsonArray)){
                            for(int index = 0; index < jsonArray.size(); index ++){
                                JSONObject object = jsonArray.getJSONObject(index);
                                JSONObject o1 = object.getJSONObject("content");
                                if ("简况".equals(object.getString("txt")) && "company".equals(object.getString("type")) && Objects.nonNull(o1)){
                                    JSONObject companyInfo = o1.getJSONObject("companyInfo");

                                    if (Objects.nonNull(companyInfo)){
                                       JSONObject issuedBy = companyInfo.getJSONObject("issuedBy");
                                        if (Objects.nonNull(issuedBy)){
                                            mainBusiness  = issuedBy.getString("mainBusiness");

                                        }
                                    }

                                }
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        if (StringUtils.isNotBlank(mainBusiness)) {
            return mainBusiness;
        }
        if (StringUtils.isNotBlank(cxt)) {
            String startStr = ",\"mainBusiness\":\"";
            do {
                cxt = cxt.substring(cxt.indexOf(startStr)+startStr.length());

            } while (cxt.contains(startStr));
            StringBuilder builder = new StringBuilder();
            char c = '"';
            for(int index = 0; index < cxt.length(); index ++) {
                if (cxt.charAt(index) == c) {
                    break;
                }else {
                    builder.append(cxt.charAt(index));
                }
            }
            return builder.toString();
        }
        return null;
    }



    public static int getId(){
        SecureRandom prng = null;
        try {
            prng = SecureRandom.getInstance("SHA1PRNG");
            return prng.nextInt();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("获取ID异常",e);
        }
    }
}
